package com.zsp.comic.controller;

import com.zsp.comic.entity.JsonResult;
import com.zsp.comic.entity.ResultCode;
import com.zsp.comic.entity.SelfUserEntity;
import com.zsp.comic.entity.User;
import com.zsp.comic.service.UserService;
import com.zsp.comic.util.ResultTool;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.util.Date;


/**
 * @author gan
 * @create 2020-12-03 21:14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PreAuthorize("hasAnyAuthority('ROLE_customer', 'ROLE_admin')")
    @PostMapping("/hasUser")
    public JsonResult hasUser(@PathParam("username") String username, @PathParam("password") String password){
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user != null){
            return ResultTool.success(true);
        }
        return ResultTool.fail();
    }

    @PostMapping("/register")
    public JsonResult register(@PathParam("username") String username, @PathParam("password") String password){
        boolean isAddress = userService.addUser(username, password, new Date());
        if (isAddress){
            return ResultTool.success(true);
        }
        return ResultTool.fail(ResultCode.USER_ACCOUNT_ALREADY_EXIST);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_customer', 'ROLE_admin')")
    @PostMapping("/changePassword")
    public JsonResult changePassword(@PathParam("username") String username, @PathParam("password") String password,
                                     @PathParam("newPassword") String newPassword,  @PathParam("confirmNewPassword") String confirmNewPassword){
        boolean isUpdateSuccess = userService.updateUser(username, password, newPassword, confirmNewPassword);
        if (isUpdateSuccess){
            return ResultTool.success(true);
        }
        return ResultTool.fail();
    }

    @PreAuthorize("hasAnyAuthority('ROLE_customer', 'ROLE_admin')")
    @PostMapping("/addUserCollect")
    public JsonResult addUserCollect(@PathParam("username") String username, @PathParam("comicId") String comicId){

        boolean isAddUserCollect = userService.addUserCollect(username, Integer.parseInt(comicId));
        if (isAddUserCollect){
            return ResultTool.success();
        }
        return ResultTool.fail();
    }

    @PreAuthorize("hasAnyAuthority('ROLE_customer', 'ROLE_admin')")
    @PostMapping("/deleteUserCollect")
    public JsonResult deleteUserCollect(@PathParam("username") String username, @PathParam("comicId") String comicId){

        boolean isDeleteUserCollect = userService.deleteUserCollect(username, Integer.parseInt(comicId));
        if (isDeleteUserCollect){
            return ResultTool.success();
        }
        return ResultTool.fail();
    }
}
